// pages/movies/more-movie/more-movie.js
// 获取全局APP
var app = getApp();
var util = require('../../../utils/utils.js')
console.log(util.http)
Page({
  /**
   * 页面的初始数据
   */
  data: {
    movies: {},
    requestUrl: "",
    totalCount: 0,
    isEmpty: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    // 获取url传过来的参数
    var category = options.category;
    // 动态设置导航栏标题
    wx.setNavigationBarTitle({
      title: category
    })
    // 获取接口地址
    var dataUrl = "";
    switch (category) {
      case "正在热映":
        dataUrl = app.globalData.doubanBase + "/v2/movie/in_theaters";
        break;
      case "即将上映":
        dataUrl = app.globalData.doubanBase + "/v2/movie/coming_soon";
        break;
      case "豆瓣Top250":
        dataUrl = app.globalData.doubanBase + "/v2/movie/top250";
        break;
    }
    this.data.requestUrl = dataUrl;
    util.http(dataUrl, this.processDoubanData)
  },
  // scrolltolower: function(event) {
  //   var nextUrl = this.data.requestUrl + "?start=" + this.data.totalCount + "&count=20";
  //   util.http(nextUrl, this.processDoubanData)
  //   // 设置loading
  //   wx.showNavigationBarLoading();
  // },
  // scrolltolower事件函数和scroll-view冲突的解决方法：放弃scroll-view，使用view组件，使用onReachBottom事件来监听页面上滑到底
  onReachBottom: function(event) {
    var nextUrl = this.data.requestUrl + "?start=" + this.data.totalCount + "&count=20";
    util.http(nextUrl, this.processDoubanData)
    // 设置loading
    wx.showNavigationBarLoading();

  },
  // 启动下拉刷新
  onPullDownRefresh: function(event) {
    var refreshUrl = this.data.requestUrl + "?start=0&count=20";
    // 下拉清空数据
    this.data.movies = {};
    this.data.isEmpty = true;
    util.http(refreshUrl, this.processDoubanData);
    wx.showNavigationBarLoading();
  },
  processDoubanData: function(moviesDouban) {
    var movies = [];
    var subject = moviesDouban.subjects;
    for (var i = 0; i < subject.length; i++) {
      var title = subject[i].title;
      if (title.length >= 6) {
        title = title.substring(0, 6) + "...";
      }
      var temp = {
        title: title,
        average: subject[i].rating.average,
        coverageUrl: subject[i].images.large,
        movieId: subject[i].id,
        stars: util.convertToStarsArray(subject[i].rating.stars)
      }
      movies.push(temp);
    }
    var totalMovies = {};
    if (!this.data.isEmpty) {
      totalMovies = this.data.movies.concat(movies);
    } else {
      totalMovies = movies;
      this.data.isEmpty = false;
    }
    this.setData({
      movies: totalMovies
    });
    this.data.totalCount += 20;
    // 关闭loading
    wx.hideNavigationBarLoading();
    // 停止下拉刷新
    wx.stopPullDownRefresh();
  },
  onMovieTap: function(event) {
    var movieId = event.currentTarget.dataset.movieid;
    wx.navigateTo({
      url: '../movie-detail/movie-detail?id=' + movieId,
    })
  }
})